package MidTerm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import java.util.List;
// GUI主类
/**
 * 提供了一个简单的GUI界面，用于模拟铁路售票系统的操作。
 * 包括车次选择、席别选择、自动售票控制、人工操作、实时统计等功能。
 */
public class TicketSystemGUI extends JFrame {
    private final TrainTicketSystem system;// 票务系统
    private  JTextArea logArea;// 日志区域
    private  JComboBox<String> trainSelector;// 车次选择
    private  JComboBox<SeatType> seatTypeSelector;// 席别选择
    private  List<Thread> autoWindows = new ArrayList<>();// 自动售票窗口
    private  JButton startAutoBtn;//  启动自动售票按钮
    private  JButton stopAutoBtn;//  停止自动售票按钮
    public TicketSystemGUI(TrainTicketSystem system) {
        this.system = system;
        initializeUI();
    }
    private void initializeUI() {
        setTitle("智能铁路售票系统");
        setSize(600, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout(10, 10));
        // 顶部控制面板
        add(createControlPanel(), BorderLayout.NORTH);
        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        add(new JScrollPane(logArea), BorderLayout.CENTER);
        // 操作面板
        add(createOperationPanel(), BorderLayout.EAST);
        // 状态栏
        JLabel statusBar = new JLabel(" 就绪 ");
        statusBar.setBorder(BorderFactory.createEtchedBorder());
        add(statusBar, BorderLayout.SOUTH);
    }
    private JPanel createControlPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 2, 10, 5));
        // 车次选择
        JPanel trainPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        trainPanel.add(new JLabel("选择车次:"));
        trainSelector = new JComboBox<>(new String[]{"G1234", "K5678"});
        trainSelector.addActionListener(e -> updateSeatTypes());
        trainPanel.add(trainSelector);
        // 席别选择
        JPanel seatPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        seatPanel.add(new JLabel("选择席别:"));
        seatTypeSelector = new JComboBox<>();
        updateSeatTypes();
        seatPanel.add(seatTypeSelector);
        // 自动售票控制
        JPanel autoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        startAutoBtn = new JButton("启动自动售票（5窗口）");
        stopAutoBtn = new JButton("停止自动售票");
        startAutoBtn.addActionListener(this::handleAutoStart);
        stopAutoBtn.addActionListener(this::handleAutoStop);
        autoPanel.add(startAutoBtn);
        autoPanel.add(stopAutoBtn);
        panel.add(trainPanel);
        panel.add(seatPanel);
        panel.add(autoPanel);
        return panel;
    }
    private JPanel createOperationPanel() {
        JPanel panel = new JPanel(new GridLayout(5, 1, 5, 8));
        panel.setBorder(BorderFactory.createTitledBorder("人工操作"));
        // 购票按钮
        JButton buyBtn = new JButton("手动购票");
        buyBtn.addActionListener(this::handleManualPurchase);
        // 退票按钮
        JButton refundBtn = new JButton("手动退票");
        refundBtn.addActionListener(this::handleManualRefund);
        // 统计按钮
        JButton statsBtn = new JButton("实时统计");
        statsBtn.addActionListener(e -> showStatistics());
        //退出系统
        JButton exitBtn = new JButton("退出系统");
        exitBtn.addActionListener(this::handleExit);
        panel.add(buyBtn);
        panel.add(refundBtn);
        panel.add(statsBtn);
        panel.add(exitBtn);
        return panel;
    }
    /**
     * 启动自动售票窗口
     */
    private void handleAutoStart(ActionEvent e) {
        int windowCount = 5;
        for (int i = 0; i < windowCount; i++) {
            int windowId = i + 1;
            Thread windowThread = new Thread(() -> {
                Random rand = new Random();
                String[] trains = {"G1234", "K5678"};
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        //  随机选择车次和席别
                        String train = trains[rand.nextInt(trains.length)];
                        TicketSystem ts = system.getTicketSystem(train);
                        if (ts == null) continue;
                        SeatType[] availableTypes = ts.getSeatTypes();
                        if (availableTypes.length == 0) {
                            logArea.append("[自动窗口"+windowId+"] "+train+" 车次所有席别已售罄\n");
                            break;
                        }
                        SeatType type = availableTypes[rand.nextInt(availableTypes.length)];
                        boolean success = system.sellTicket(train, type, windowId);
                        SwingUtilities.invokeLater(() -> {
                            logArea.append(String.format("[自动窗口%d] %s 车次：%s 席别：%s\n",
                                    windowId,
                                    success ? "售票成功" : "余票不足",
                                    train,
                                    type));
                            if (!success) { // 补充余票信息
                                int remaining = ts.getRemainingSeats(type);
                                logArea.append(String.format("[自动窗口%d] 当前余票：%s 车次 %s 席别 剩余：%d\n",
                                        windowId, train, type, remaining));
                            }
                        });
                        checkAndStopIfSoldOut();
                        // 随机等待时间 随机休眠
                        Thread.sleep(rand.nextInt(500) + 200);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
            windowThread.start();
            autoWindows.add(windowThread);
        }
    }
    private void checkAndStopIfSoldOut() {
        boolean allSoldOut = true;
        String[] trains = {"G1234", "K5678"}; // 从系统获取所有车次
        for (String train : trains) {
            TicketSystem ts = system.getTicketSystem(train);
            if (ts == null) continue;
            for (SeatType type : ts.getSeatTypes()) {
                if (ts.getRemainingSeats(type) > 0) {
                    allSoldOut = false;
                    break;
                }
            }
            if (!allSoldOut) break;
        }
        if (allSoldOut) {
            SwingUtilities.invokeLater(() -> {
                handleAutoStop(null);
                logArea.append("所有车票已售罄，自动停止售票窗口\n");
            });
        }
    }
    /**
     * 停止所有自动售票窗口
     */
    private void handleAutoStop(ActionEvent e) {
        autoWindows.forEach(Thread::interrupt);
        autoWindows.clear();
        logArea.append("所有自动售票窗口已停止\n");
    }
    private void handleManualPurchase(ActionEvent e) {
        String train = (String) trainSelector.getSelectedItem();
        SeatType type = (SeatType) seatTypeSelector.getSelectedItem();
        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() {
                boolean success = system.sellTicket(train, type, 0);
                String status = success ? "购票成功" : "购票失败";
                int remaining = system.getTicketSystem(train).getRemainingSeats(type);
                logArea.append(String.format("[人工窗口] %s 车次：%s 席别：%s 票数剩余：%d\n",
                        status, train, type, remaining));
                return null;
            }
        }.execute();
    }
    private void handleManualRefund(ActionEvent e) {
        String ticketId = JOptionPane.showInputDialog(this, "请输入完整票号：", "退票操作", JOptionPane.QUESTION_MESSAGE);
        if (ticketId != null && !ticketId.isEmpty()) {
            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {
                    try {
                        String train = ticketId.split("-")[0];
                        boolean success = system.refundTicket(train, ticketId);
                        logArea.append("[人工退票] " + (success ? "退票成功" : "退票失败") + ": " + ticketId + "\n");
                    } catch (Exception ex) {
                        logArea.append("无效票号格式\n");
                    }
                    return null;
                }
            }.execute();
        }
    }
    private void showStatistics() {
        String train = (String) trainSelector.getSelectedItem();
        TicketSystem ts = system.getTicketSystem(train);
        if (ts == null) return;
        StringBuilder stats = new StringBuilder();
        stats.append("=== ").append(train).append(" 实时统计 ===\n");
        ts.getSeatCounters().forEach((type, counter) -> {
            int sales = ts.getTypeSales().get(type).get();
            stats.append(String.format("%-8s: 余票 %3d | 已售 %3d\n",
                    type, counter.get(), sales));
        });
        JOptionPane.showMessageDialog(this, stats.toString());
    }
    // 更新可选席别列表
    private void updateSeatTypes() {
        SwingUtilities.invokeLater(() -> {
            String train = (String) trainSelector.getSelectedItem();
            TicketSystem ts = system.getTicketSystem(train);
            seatTypeSelector.removeAllItems();
            if (ts != null) {
                Arrays.stream(ts.getSeatTypes())
                        .forEach(seatTypeSelector::addItem);
            }
        });
    }
    public static void main(String[] args) {
        // 初始化系统
        TrainTicketSystem system = new TrainTicketSystem();
        system.addTrain("G1234", new SeatConfig()
                .add(SeatType.SECOND_CLASS, 50)
                .add(SeatType.BUSINESS_SEAT, 10));
        system.addTrain("K5678", new SeatConfig()
                .add(SeatType.SOFT_SLEEPER, 20)
                .add(SeatType.HARD_SEAT, 60));
        // 启动GUI
        SwingUtilities.invokeLater(() -> {
            TicketSystemGUI gui = new TicketSystemGUI(system);
            gui.setVisible(true);
        });
    }
    //退出系统处理方法
    private void handleExit(ActionEvent e) {
        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要退出系统吗？",
                "退出确认",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {
            handleAutoStop(null); // 先停止所有自动售票线程
            dispose(); // 关闭窗口
            System.exit(0); // 终止JVM
        }
    }
}




